import plays from './plays.json'
export default function statement(invoice, plays) {
  const statementData = {}
  return renderPlainText(statementData, invoice, plays);
}
function renderPlainText(statementData, invoice, plays) {
  let res = `【用户${invoice.customer}的票据单】`;
  // 🔺第一步：拆分循环 数据集中
  // let totalAmount = 0;
  for (let perf of invoice.performance) {
    res += ` ${playFor(perf).name}: ${usd(amountFor(perf)/100)} (${perf.audience} 座)`;
  }
  // 🔺第三步：内联变量 避免过多的局部变量
  res += ` 所欠贷款是 ${usd(totalAmount(invoice)/100)}`;
  res += ` 你赚了 ${totalVolumeCredits(invoice)} 分`;
  return res;
} 
// 🔺第二步：提炼求和函数
function totalVolumeCredits(invoice) {
  let res = 0;
  for (let perf of invoice.performance) {
    res += volumeCreditsFor(perf);
  }
  return res;
}
// 🔺第二步：提炼求和函数
function totalAmount(invoice) {
  let res = 0;
  for (let perf of invoice.performance) {
    res += amountFor(perf);
  }
  return res;
}
function amountFor(aPerformance) {
  let res = 0
  switch(playFor(aPerformance).type) {
    case "悲剧":
      res = 40000;
      if (aPerformance.audience > 30) {
        res += 1000 * (aPerformance.audience - 30);
      }
      break;
    case "喜剧": 
    res = 30000;
      if (aPerformance.audience > 20) {
        res += 10000 + 500 * (aPerformance.audience - 20);
      }
      res += 300 * aPerformance.audience
      break
    default:
      throw new Error(`未知的类型: ${play.type}`)
  }
  return res
}
function playFor(aPerformance) {
  return plays[aPerformance.playID]
}
function volumeCreditsFor(aPerformance) {
  let res = 0;
  res += Math.max(aPerformance.audience - 30, 0);
  if ("喜剧" === playFor(aPerformance).type) res += Math.floor(aPerformance.audience / 5);
  return res;
}
function usd(aNumber) {
  return new Intl.NumberFormat("en-US", {style: "currency", currency: "USD", minimumFractionDigits: 2}).format(aNumber)
}